package com.example.lib_adapter

import android.util.SparseArray
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_common.GlideUtils

class BaseViewHolder(itemView:View):RecyclerView.ViewHolder(itemView) {

    var list=SparseArray<View>()

    //根据id获取View
    fun <V:View> getView(id:Int):V{
        var v:V?=null
        v=list.get(id) as V?
        if(v!=null){
            return v
        }
        //如果缓存中没有，就新获取控件
        v=find(id)
        if(v!=null)
            list.put(id,v)
        return v
    }


    //根据id获取控件对象
    fun <V:View> find(id:Int):V{
        return itemView.findViewById(id)
    }

    //给TextView赋值
    fun setText(id:Int,value:String){
        if(value.isNullOrEmpty()){
            return
        }
        val tv = getView<TextView>(id)
        if(tv==null){
            return
        }
        tv.setText(value)
    }

    fun setImage(id:Int,url:String){
        val iv = getView<ImageView>(id)
        if(iv==null){
            return
        }
        GlideUtils.loadRoundImage(iv.context,url,iv)
    }

    fun setImage(id:Int,resId:Int){
        val iv = getView<ImageView>(id)
        if(iv==null){
            return
        }
        GlideUtils.loadRoundImage(iv.context,resId,iv)
    }
}